package com.ai.networking.netty.client;


import com.ai.entity.comm.SysNetty;
import com.ai.networking.netty.decoder.L1ToSysMessageDecoder;
import com.ai.networking.netty.handler.ClientHandler;
import com.ai.networking.netty.handler.HearBeatHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;

/**
 * netty 客户端
 */
@Slf4j
public class BootNettyClient implements Runnable {
    SysNetty sysNetty;

    public BootNettyClient(SysNetty sysNetty) {
        this.sysNetty = sysNetty;
    }

    public void connect(SysNetty sysNetty) {
        // 客户端的NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        try {
            // 配置Bootstrap
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.RCVBUF_ALLOCATOR,
                            new AdaptiveRecvByteBufAllocator(256, 256, 65535))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new L1ToSysMessageDecoder());
                            ch.pipeline().addLast(new HearBeatHandler());
                            ch.pipeline().addLast(new ClientHandler(sysNetty.getIp(), sysNetty.getPort()));
                        }
                    });

            bootstrap.localAddress(18008); // 本地绑定地址

            // 连接服务端
            ChannelFuture futureTcp = bootstrap.connect(sysNetty.getIp(), sysNetty.getPort());

            // 添加连接成功/失败的监听器
            futureTcp.addListener(future -> {
                if (future.isSuccess()) {
                    log.info("netty client 连接成功! 连接的服务器ip:{}，端口:{}", sysNetty.getIp(), sysNetty.getPort());
                } else {
                    log.error("netty client 连接失败! 连接的服务器ip:{}，端口:{}，异常: {}", sysNetty.getIp(), sysNetty.getPort(), future.cause().getMessage());
                }
            });

            // 监听连接关闭事件
            futureTcp.channel().closeFuture().addListener(future -> {
                group.shutdownGracefully(); // 优雅关闭连接
                log.info("================NettyClient 关闭服务器通道！！========================");
            });
        } catch (Exception e) {
            log.error("Netty 客户端初始化时出现异常: " + e.getMessage(), e);
            group.shutdownGracefully();  // 如果初始化失败，确保关闭资源
        }
    }

    @Override
    public void run() {
        this.connect(sysNetty);
    }
}
